package com.alex.utils.http.proxy;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class SocksProxySocketFactory implements SchemeSocketFactory {

	public static SocksProxySocketFactory get() {
		return Holder.INSTANCE;
	}
	
	private static class Holder {
		private static SocksProxySocketFactory INSTANCE = new SocksProxySocketFactory();
	}

	private ThreadLocal<SocksProxy> proxy = new ThreadLocal<SocksProxy>();
	
	private SocksProxySocketFactory() {
	}
	
	public void setProxy(SocksProxy proxy) {
		this.proxy.set(proxy);
	}

	@Override
	public Socket createSocket(HttpParams params) throws IOException {
		if (proxy.get() != null) {
			return new Socket(new Proxy(Type.SOCKS, new InetSocketAddress(proxy.get().getHost(), proxy.get().getPort())));
		} 
		return new Socket();
	}

	@Override
	public Socket connectSocket(Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpParams params)
			throws IOException, UnknownHostException, ConnectTimeoutException {
		sock.connect(remoteAddress, (int) HttpConnectionParams.getConnectionTimeout(params));
		return sock;
	}

	@Override
	public boolean isSecure(Socket sock) throws IllegalArgumentException {
		return false;
	}
}
